<template>
  <div class="check-result-page">
    <div class="header-row">
      <h1 class="page-title">检查结果管理</h1>
      <div class="stat">共 <b>{{ filtered.length }}</b> 条</div>
    </div>

    <el-card class="filter-card" shadow="hover">
      <el-form :inline="true" :model="query" @submit.prevent>
        <el-form-item label="病历号">
          <el-input v-model.trim="query.caseNumber" placeholder="病历号" clearable @keyup.enter="load" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model.trim="query.realName" placeholder="患者姓名" clearable @keyup.enter="load" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="load">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card" shadow="hover">
      <el-table :data="paged" :loading="loading" stripe height="480" empty-text="暂无已出结果记录" @row-dblclick="showDetail">
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="patientName" label="姓名" width="110" />
        <el-table-column prop="patientCaseNumber" label="病历号" width="130" />
        <el-table-column prop="checkInfo" label="检查信息" min-width="160" show-overflow-tooltip />
        <el-table-column prop="checkResult" label="结果摘要" min-width="200" show-overflow-tooltip />
        <el-table-column prop="checkTime" label="检查时间" width="160">
          <template #default="{ row }">{{ formatTime(row.checkTime) }}</template>
        </el-table-column>
        <el-table-column prop="inputcheckEmployeeId" label="结果医生ID" width="110" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" @click="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager-wrapper" v-if="filtered.length > pageSize">
        <el-pagination background layout="prev, pager, next" :page-size="pageSize" :current-page="pageNum" :total="filtered.length" @current-change="(p)=>{pageNum=p}" />
      </div>
    </el-card>

    <el-dialog v-model="detailVisible" title="检查结果详情" width="720px" destroy-on-close>
      <el-descriptions :column="2" border size="small">
        <el-descriptions-item label="ID">{{ detail.id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="挂号ID">{{ detail.registerId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ detail.patientName || rowCache.patientName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="病历号">{{ detail.patientCaseNumber || rowCache.patientCaseNumber || '-' }}</el-descriptions-item>
        <el-descriptions-item label="年龄/性别">{{ (detail.patientAge ?? rowCache.patientAge) ?? '-' }}/{{ (detail.patientGender ?? rowCache.patientGender) ?? '-' }}</el-descriptions-item>
        <el-descriptions-item label="检查信息" :span="2">{{ detail.checkInfo || rowCache.checkInfo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="检查部位" :span="2">{{ detail.checkPosition || rowCache.checkPosition || '-' }}</el-descriptions-item>
        <el-descriptions-item label="检查结果" :span="2">{{ detail.checkResult || rowCache.checkResult || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.checkRemark || rowCache.checkRemark || '-' }}</el-descriptions-item>
        <el-descriptions-item label="检查时间">{{ formatTime(detail.checkTime || rowCache.checkTime) }}</el-descriptions-item>
        <el-descriptions-item label="结果医生ID">{{ detail.inputcheckEmployeeId || rowCache.inputcheckEmployeeId || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible=false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchAll, fetchDetail } from '@/api/checkRequest'

const loading = ref(false)
const list = ref([])
const query = reactive({ caseNumber: '', realName: '' })
const pageNum = ref(1)
const pageSize = 12

const detailVisible = ref(false)
const detail = ref({})
// 行点击时临时缓存，避免接口缺失字段导致弹窗空白
const rowCache = reactive({})

const filtered = computed(()=>{
  return list.value.filter(r => r.checkState === '已出结果' &&
    (!query.caseNumber || (r.patientCaseNumber && r.patientCaseNumber.includes(query.caseNumber))) &&
    (!query.realName || (r.patientName && r.patientName.includes(query.realName)))
  )
})

const paged = computed(()=>{
  const start = (pageNum.value-1)*pageSize
  return filtered.value.slice(start, start+pageSize)
})

function formatTime(t){
  if(!t) return '-'
  const d = new Date(t)
  const p = n=>String(n).padStart(2,'0')
  return `${d.getFullYear()}-${p(d.getMonth()+1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
}

async function load(){
  loading.value = true
  try {
    const res = await fetchAll()
    list.value = res.data || []
    pageNum.value = 1
  } catch(e){
    ElMessage.error(e.message || '加载失败')
  } finally { loading.value = false }
}

function resetQuery(){
  query.caseNumber=''; query.realName=''; load()
}

async function showDetail(row){
  // 先缓存当前行，保证最基本信息可见
  Object.assign(rowCache, row || {})
  detail.value = { ...row } // 初始先用行数据填充
  detailVisible.value = true
  try {
    const res = await fetchDetail(row.id)
    // 只在成功后合并（保留行数据做 fallback）
    if(res && res.data){
      detail.value = { ...rowCache, ...res.data }
    }
  } catch(e){
    // 接口失败时仍保留行数据
    ElMessage.warning('详情接口获取失败，显示列表数据')
  }
}

onMounted(()=> load())
</script>

<style scoped>
.check-result-page { padding:14px; }
.header-row { display:flex; align-items:center; gap:24px; margin-bottom:10px; }
.page-title { font-size:24px; font-weight:600; margin:0; }
.stat { font-size:14px; color:#606266; }
.stat b { color:#409eff; }
.filter-card { border-radius:14px; margin-bottom:14px; }
.list-card { border-radius:14px; }
.pager-wrapper { display:flex; justify-content:flex-end; margin-top:12px; }
</style>
